package com.qujia.station.service.impl;

import com.qujia.common.core.domain.AjaxResult;
import com.qujia.coupon.domain.*;
import com.qujia.coupon.mapper.CouponInfoMapper;
import com.qujia.coupon.mapper.CouponIssueMapper;
import com.qujia.coupon.mapper.CouponUserMapper;
import com.qujia.customer.domain.ActivityMessagePushRecord;
import com.qujia.customer.service.ActivityMessagePushRecordService;
import com.qujia.station.domain.CouponActivity;
import com.qujia.station.domain.DrawCoupon;
import com.qujia.station.domain.PayOrder;
import com.qujia.station.mapper.CouponActivityMapper;
import com.qujia.station.service.CouponActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: LogicQin
 * @Date: 2023/8/4 12:09
 * @Description:
 */

@Service
@Slf4j
public class CouponActivityServiceImpl implements CouponActivityService {
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    @Autowired
    private CouponIssueMapper couponIssueMapper;
    @Autowired
    private CouponUserMapper couponUserMapper;
    @Autowired
    private CouponInfoMapper couponInfoMapper;
    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;


    @Override
    public void addCouponActivity(CouponActivity couponActivity) {
        // 生成优惠券活动ID
        int i = 0;
        Random random = new Random();
        String result = "";
        String result1 = "";
        for (int m = 0; m < 4; m++) {
            result += random.nextInt(10);
        }
        for (int mm = 0; mm < 4; mm++) {
            result1 += random.nextInt(10);
        }
        String tempTime = System.currentTimeMillis() + "";
        String ordNo = "" + result1 + tempTime.substring(5) + result;

        // 设置生成的ID到优惠券活动对象
        couponActivity.setId(ordNo);

        // 创建一个新的Date对象，表示当前时间
        Date currentTime = new Date();

// 定义日期时间格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 格式化当前时间为字符串
        String formattedDateTime = formatter.format(currentTime);

// 将格式化后的字符串传递给 couponActivity
        couponActivity.setCreateTime(formattedDateTime);

// 调用couponActivityMapper的addCouponActivity方法进行新增操作
        couponActivity.setActivityStatus("0");


        couponActivityMapper.addCouponActivity(couponActivity);

        //wx推送记录
        ActivityMessagePushRecord record = new ActivityMessagePushRecord();
        record.setContent(couponActivity.getWxContent());
        record.setSendFlag(couponActivity.getSendFlag());
        record.setStatus(0);
        record.setBusinessId(Long.parseLong(couponActivity.getId()));
        record.setBusinessName(ActivityMessagePushRecord.COUPON_ACTIVITY);
        activityMessagePushRecordService.insert(record);

        // 如果issueIds不为空，插入优惠券活动和发放的关联关系
        List<String> issueIds = couponActivity.getIssueIds();
        if (issueIds != null && !issueIds.isEmpty()) {
            for (String issueId : issueIds) {
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("activityId", ordNo); // 使用生成的ID
                paramMap.put("issueId", issueId);
                couponActivityMapper.insertCouponActivityRelaIssue(paramMap);
            }
        }
        // 如果couponInfos不为空，插入优惠券活动和优惠券设置的关联关系
        List<CouponInfo> couponInfos = couponActivity.getCouponInfos();
        if (couponInfos != null && !couponInfos.isEmpty()) {
            for (CouponInfo couponInfo : couponInfos) {
                couponInfo.setCouponActivityId(ordNo);
                couponActivityMapper.addMoonCountAndDayCount(couponInfo);
            }
        }
        if (couponActivity.getIssueType().equals("1")) {
            if (couponActivity.getDistributionType().equals("1")) {
                List<Threshold> amountIssueIdList = couponActivity.getThresholdLadder();
                for (Threshold issueIdMap : amountIssueIdList) {
                    List<String> issueIdList = issueIdMap.getCouponList();
                    BigDecimal thresholdAmt = issueIdMap.getValue();
                    for (String issueId : issueIdList) {
                        Map<String, String> paramMap = new HashMap<>();
                        paramMap.put("activityId", ordNo); // 使用生成的ID
                        paramMap.put("issueId", issueId);
                        paramMap.put("thresholdAmt", thresholdAmt.toString());
                        paramMap.put("createBy", couponActivity.getCreateBy()); // 获取创建人信息
                        couponActivityMapper.insertCouponActivityLadder(paramMap);
                    }
                }
            }
        }

    }

    @Override
    public void deleteCouponActivityById(String id) {
        couponActivityMapper.deleteCouponActivityById(id);
        couponActivityMapper.deleteCouponActivityCountById(id);
    }

    @Override
    public AjaxResult amtForList(List<String> issueIds) {
        List<CouponInfo> a =  couponActivityMapper.amtForList(issueIds);
        AjaxResult AjaxResulta;
        if (a.size()>0){
            AjaxResulta = AjaxResult.success(a);
        }else{
            AjaxResulta = AjaxResult.error("没数据");
        }
  return AjaxResulta;

    }

//    @Override
//    public AjaxResult addMoonCountAndDayCount(List<CouponInfo> couponInfos) {
//
//        List<CouponInfo> a =  couponActivityMapper.amtForList(issueIds);
//        AjaxResult AjaxResulta;
//        if (a.size()>0){
//            AjaxResulta = AjaxResult.success(a);
//        }else{
//            AjaxResulta = AjaxResult.error("没数据");
//        }
//        return AjaxResulta;
//
//    }


    //    发多人
//    {
//        "mobilePhoneList": [
//        "18664806604"
//],
//        "couponIssueIdList": [
//        "8725773425032491",
//                "7431773398111594"
//],
//        "enterpriseId": 174
//               +ccsdId逻辑
//    }
    @Override
    public AjaxResult sendCoupon(DrawCoupon drawCoupon) {
        Integer activityType = drawCoupon.getActivityType();
        AjaxResult a = AjaxResult.error("优惠券手动发放失败");
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        List<String> couponIssueIdList = drawCoupon.getCouponIssueIdList();
        List<String> mobilePhoneList = drawCoupon.getMobilePhoneList();
        if (couponIssueIdList != null && !couponIssueIdList.isEmpty() && mobilePhoneList != null && !mobilePhoneList.isEmpty()) {


//校验
            for (String couponIssueId : couponIssueIdList) {
                for (String mobilePhone : mobilePhoneList) {
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("mobilePhone", mobilePhone);
                    paramMap.put("couponIssueId", couponIssueId);
                    CouponIssue souponIssue = couponIssueMapper.selectCouponIssueById(couponIssueId);
                    int userIssueGiveCount = couponUserMapper.selectUserIssueGiveCount(paramMap);
                    CouponUserGiveCount cugc = couponUserMapper.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(couponIssueId).randomFlag(drawCoupon.getRandomFlag()).build());
                    Integer couponinfoId = couponIssueMapper.getCouponInfoIdByIssueId(Long.parseLong(couponIssueId));
                    CouponInfo couponInfo = couponInfoMapper.selectCouponInfoById(couponinfoId);
                    if (couponInfo != null && couponInfo.getGetCouponNum() >= couponInfo.getCouponNum()) {
                        return AjaxResult.error("优惠券手动发放失败优惠券" + couponInfo.getCouponRemark() + "已不能再领");
                    }
                    if (souponIssue != null && userIssueGiveCount >= souponIssue.getGiveCount()) {
                        return AjaxResult.error("优惠券手动发放失败用户已不能再领");
                    }
                    if (souponIssue != null && userIssueGiveCount >= souponIssue.getGiveCount()) {
                        return AjaxResult.error("优惠券手动发放失败用户已不能再领");
                    }
                    if (souponIssue == null || !souponIssue.getStatus().equals("1")) {
                        return AjaxResult.error("优惠券状态不对");
                    }
                    if (cugc != null && cugc.getIssueGiveCount() + 1 >= souponIssue.getGiveLimit()) {
                        return AjaxResult.error("优惠券剩余数量不足");
                    } else if (1 >= souponIssue.getGiveLimit()) {
                        return AjaxResult.error("优惠券剩余数量不足");
                    }


                }

            }
//            使用
            int counter = 1; // 初始化计数器
            List<CouponUser> saveCouUserList = new ArrayList<>();
            List<Integer> updateTemIdsCountList = new ArrayList<>();
            for (String couponIssueId : couponIssueIdList) {
                for (String mobilePhone : mobilePhoneList) {
                    Integer couponinfoId = couponIssueMapper.getCouponInfoIdByIssueId(Long.parseLong(couponIssueId));
                    drawCoupon.setCouponIssueId(couponIssueId);

                    drawCoupon.setCouTemIds(couponinfoId.toString());
                    // 生成后三位的字符串，保证至少有三位，不足的在前面补0
                    String counterString = String.format("%03d", counter);

                    // 获取原始的 randomFlag，即去掉后三位的部分
                    String originalRandomFlag = drawCoupon.getRandomFlag().substring(0, drawCoupon.getRandomFlag().length() - 3);

                    // 构建新的 randomFlag，将原始部分与后三位替换为循环数
                    String newRandomFlag = originalRandomFlag + counterString;

                    // 更新 drawCoupon 的 randomFlag
                    drawCoupon.setRandomFlag(newRandomFlag);

                    // 增加计数器
                    counter++;
//                    CouponIssue couponIssue = couponIssueMapper.selectCouponIssueById(couponinfoId.toString());
                    CouponInfo couponInfo = couponInfoMapper.selectCouponInfoById(couponinfoId);
                    Date startTime = new Date();     //开始时间
                    Date endTime = new Date();       //结束时间

                    switch (couponInfo.getEffectiveTimeType()) {
                        case "1":   //固定时间
                            //startTime = couponTemplate.getEffectiveTimeStart();
                            endTime = couponInfo.getEffectiveTimeEnd();
                            break;
                        case "2":   //领取后有效天数
                            startTime = new Date();
                            Calendar instance = Calendar.getInstance();
                            instance.setTime(new Date());
                            instance.add(Calendar.DATE, couponInfo.getEffectiveDayNum());
                            endTime = instance.getTime();
                            break;
                    }
                    saveCouUserList.add(CouponUser.builder()
                            .mobilePhone(mobilePhone)
                            .issueId(couponIssueId)
                            .couponId(couponinfoId.longValue())
                            .couponIsUsed("0")
                            .couponNo(useMD5(drawCoupon.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                            .enterpriseId(drawCoupon.getEnterpriseId())
                            .ccsdId(drawCoupon.getCcsdId())
                            .couponGetTime(startTime)
                            .activityType(activityType)
                            .activityName("-")
                            .randomFlag(drawCoupon.getRandomFlag())
                            .couponEffectiveTime(endTime)
                            .build());
                    updateTemIdsCountList.add(couponinfoId);

                    CouponUserGiveCount cugc = couponUserMapper.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(couponIssueId).randomFlag(drawCoupon.getRandomFlag()).build());
                    if (null != cugc) {
                        couponUserMapper.updateCouponUserGiveCount(CouponUserGiveCount.builder()
                                .randomFlag(drawCoupon.getRandomFlag())
                                .issueGiveCount(1 + cugc.getIssueGiveCount())
                                .mobilePhone(mobilePhone)
                                .couponIssueId(couponIssueId)
                                .build());
                    } else {
                        couponUserMapper.insertCouponUserGiveCount(CouponUserGiveCount.builder()
                                .randomFlag(drawCoupon.getRandomFlag())
                                .issueGiveCount(1)
                                .mobilePhone(mobilePhone)
                                .couponIssueId(couponIssueId)
                                .build());
                    }
                }
            }

            if (null != saveCouUserList && saveCouUserList.size() > 0) {
                int i = couponUserMapper.saveBatchCouponUser(saveCouUserList);
                log.info("批量保存的用户优惠券数量：" + i);
                CouponDeduction couponDeduction = new CouponDeduction();
                couponDeduction.setUpdateTemIdsCountList(updateTemIdsCountList);
                couponDeduction.setPhoneSize(mobilePhoneList.size());
                int y = couponUserMapper.updateBatchCouponTemplate(couponDeduction);
                log.info("批量更新的优惠券模板减少的模板优惠券数量：" + mobilePhoneList.size());
                a = AjaxResult.success("发放成功");
            } else {
                return AjaxResult.error("没有可以保存的优惠券");
            }


        } else {
            a = AjaxResult.error("缺少用户手机号或可用的优惠券");
        }
        return a;
    }


    public static String useMD5(String passWord) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(passWord.getBytes());
            return getHashString(digest);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;

    }

    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString().toLowerCase();
    }

    @Override
    public AjaxResult checkCouponActivity(CouponActivity couponActivity) {
        List<String> issueIds = couponActivity.getIssueIds();
        if (issueIds == null || issueIds.isEmpty()) {
            return AjaxResult.error("绑定优惠券不能为空");
        }

        if (couponActivity.getIssueType().equals("1")) {
            if (couponActivity.getDistributionType().equals("0")) {
                BigDecimal activityThreshold = couponActivity.getActivityThreshold();
                if (activityThreshold == null || activityThreshold.compareTo(BigDecimal.ZERO) == 0) {
                    return AjaxResult.error("活动门槛金额不能为空");
                }
            } else if (couponActivity.getDistributionType().equals("1")) {
                List<Threshold> amountIssueIdList = couponActivity.getThresholdLadder();
                if (amountIssueIdList == null || amountIssueIdList.isEmpty()) {
                    return AjaxResult.error("活动门槛阶梯关联列表不能为空");
                }
                Set<BigDecimal> valueSet = new HashSet<>();
                for (Threshold threshold : amountIssueIdList) {
                    BigDecimal value = threshold.getValue();
                    if (value == null) {
                        return AjaxResult.error("阶梯值不能为空");
                    }

                    if (valueSet.contains(value)) {
                        return AjaxResult.error("阶梯值重复");
                    }
                    valueSet.add(value);
                }
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startTime = format.parse(couponActivity.getActivityStartTime());
            Date endTime = format.parse(couponActivity.getActivityEndTime());

            if (startTime.before(endTime)) {

            } else {
                return AjaxResult.error("时间校验失败：开始时间在结束时间之后");
            }

            Date currentTime = new Date(); // 获取当前时间
            if (endTime.before(currentTime)) {
                return AjaxResult.error("时间校验失败：结束时间在当前时间之前");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 所有校验通过，返回成功
        return AjaxResult.success();
    }

    @Override
    public void updateCouponActivity(CouponActivity couponActivity) {
        CouponActivity couponActivityById = getCouponActivityById(couponActivity.getId());
        if (couponActivityById.getActivityStatus().equals("0")) {
            //如果是未开始
            ActivityMessagePushRecord record = new ActivityMessagePushRecord();
            record.setBusinessName(ActivityMessagePushRecord.COUPON_ACTIVITY);
            record.setBusinessId(Long.parseLong(couponActivity.getId()));
            List<ActivityMessagePushRecord> query = activityMessagePushRecordService.query(record);
            if (query.size() > 0) {
                ActivityMessagePushRecord p = query.get(0);
                p.setSendFlag(couponActivity.getSendFlag());
                p.setContent(couponActivity.getWxContent());
                activityMessagePushRecordService.update(p);
            } else {
                //wx推送记录
                record.setContent(couponActivity.getWxContent());
                record.setSendFlag(couponActivity.getSendFlag());
                record.setStatus(0);
                activityMessagePushRecordService.insert(record);
            }
        }

        // 创建一个新的Date对象，表示当前时间
        Date currentTime = new Date();
// 设置couponActivity的createTime字段为当前时间
        couponActivity.setUpdateTime(currentTime);
        couponActivityMapper.updateCouponActivity(couponActivity);
        List<String> issueIds = couponActivity.getIssueIds();
        couponActivityMapper.deleteCouponActivityRelaById(couponActivity.getId());
        couponActivityMapper.deleteCouponActivityCountById(couponActivity.getId());
        if (issueIds != null && !issueIds.isEmpty()) {
            for (String issueId : issueIds) {
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("activityId", couponActivity.getId()); // 使用生成的ID
                paramMap.put("issueId", issueId);
                couponActivityMapper.insertCouponActivityRelaIssue(paramMap);
            }
        }
        // 如果couponInfos不为空，插入优惠券活动和优惠券设置的关联关系
        List<CouponInfo> couponInfos = couponActivity.getCouponInfos();
        if (couponInfos != null && !couponInfos.isEmpty()) {
            for (CouponInfo couponInfo : couponInfos) {
                couponInfo.setCouponActivityId(couponActivity.getId());
                couponActivityMapper.addMoonCountAndDayCount(couponInfo);
            }
        }
        if (couponActivity.getIssueType().equals("1")) {
            if (couponActivity.getDistributionType().equals("1")) {
                List<Threshold> amountIssueIdList = couponActivity.getThresholdLadder();
                couponActivityMapper.deleteCouponActivityLadder(couponActivity.getId());
                for (Threshold issueIdMap : amountIssueIdList) {
                    List<String> issueIdList = issueIdMap.getCouponList();
                    BigDecimal thresholdAmt = issueIdMap.getValue();
                    for (String issueId : issueIdList) {
                        Map<String, String> paramMap = new HashMap<>();
                        paramMap.put("activityId", couponActivity.getId()); // 使用生成的ID
                        paramMap.put("issueId", issueId);
                        paramMap.put("thresholdAmt", thresholdAmt.toString());
                        paramMap.put("createBy", couponActivity.getUpdateBy()); // 获取创建人信息
                        couponActivityMapper.insertCouponActivityLadder(paramMap);
                    }
                }
            }
        }

    }


    @Override
    public int batchDeleteCouponActivities(List<String> idList) {
        return couponActivityMapper.batchDeleteCouponActivities(idList);
    }

    @Override
    public CouponActivity getCouponActivityById(String id) {
        List<String> issueIds = couponActivityMapper.getIssueIdsByActivityId(id); // 获取 issue_id 数据列表
        List<CouponInfo> couponInfos = couponActivityMapper.getCouponIdsByActivityId(id); // 获取 issue_id 数据列表
        CouponActivity couponActivity = couponActivityMapper.getCouponActivityById(id); // 获取活动详情
        couponActivity.setCouponInfos(couponInfos);
        // 非空判断并填充数据
        if (issueIds != null && !issueIds.isEmpty()) {
            couponActivity.setIssueIds(issueIds);
        }
        List<Map<String, Object>> issueLadder = couponActivityMapper.getIssueLadderByActivityId(id);
        if (couponActivity.getIssueType().equals("1")) {
            if (couponActivity.getDistributionType().equals("1")) {
                List<Threshold> thresholdList = new ArrayList<>();
                Map<BigDecimal, List<String>> valueToCouponMap = new LinkedHashMap<>();
                for (Map<String, Object> entry : issueLadder) {
                    Object thresholdAmtObj = entry.get("threshold_amt");
                    if (thresholdAmtObj instanceof BigDecimal) {
                        BigDecimal thresholdAmt = (BigDecimal) thresholdAmtObj;
                        String issueId = entry.get("issue_id").toString();

                        if (!valueToCouponMap.containsKey(thresholdAmt)) {
                            valueToCouponMap.put(thresholdAmt, new ArrayList<>());
                        }
                        valueToCouponMap.get(thresholdAmt).add(issueId);
                    }
                }

                for (Map.Entry<BigDecimal, List<String>> valueCouponEntry : valueToCouponMap.entrySet()) {
                    Threshold threshold = new Threshold();
                    threshold.setValue(valueCouponEntry.getKey());
                    threshold.setCouponList(valueCouponEntry.getValue());
                    thresholdList.add(threshold);
                }
                couponActivity.setThresholdLadder(thresholdList);
            }
        }
        ActivityMessagePushRecord pushRecord = new ActivityMessagePushRecord();
        pushRecord.setBusinessId(Long.parseLong(id));
        pushRecord.setBusinessName(ActivityMessagePushRecord.COUPON_ACTIVITY);
        List<ActivityMessagePushRecord> records = activityMessagePushRecordService.query(pushRecord);
        if (records.size() > 0) {
            ActivityMessagePushRecord record = records.get(0);
            couponActivity.setSendFlag(record.getSendFlag());
            couponActivity.setWxContent(record.getContent());
        } else {
            couponActivity.setSendFlag(0);
        }

        return couponActivity;
    }


    @Override
    public List<CouponActivity> getAllCouponActivities(CouponActivity couponActivity) {
        return couponActivityMapper.getAllCouponActivities(couponActivity);
    }

    @Override
    public void updateActivityStatus(String activityId, String activityStatus) {
        Map<String, Object> params = new HashMap<>();
        params.put("activityId", activityId);
        params.put("activityStatus", activityStatus);
        couponActivityMapper.updateActivityStatus(params);
        if (activityStatus.equals("1")) {
            //启动优惠券活动推送消息
            if (StringUtils.isNotEmpty(activityId)) {
                activityMessagePushRecordService.sendWxMessage(Long.parseLong(activityId), ActivityMessagePushRecord.COUPON_ACTIVITY);
            }
        }
    }

    @Override
    public void physicalCardSendCoupon(PayOrder payOrder) {
        try {
            List<String> couponIssueIds = new ArrayList<>();
            String activityId = this.checkCouponActivity(payOrder.getEnterpriseId().intValue(), payOrder, 0.0);
            Map<String, Object> activity = couponActivityMapper.getActivityAllByActivityId(activityId);
            BigDecimal receivedAmt;
            if (activity.isEmpty()) {
            } else {
                receivedAmt = payOrder.getAmt() != null ? payOrder.getAmt() : BigDecimal.ZERO;
                if ((Integer) activity.get("distribution_type") == 0) {
                    BigDecimal activityThreshold = new BigDecimal(activity.get("activity_threshold").toString());
                    if (receivedAmt.compareTo(activityThreshold) >= 0) {
                        couponIssueIds = this.getIssueIdsByActivityId(activityId);
                    }
                } else if ((Integer) activity.get("distribution_type") == 1) {
                    couponIssueIds = this.getIssueIdsByActivityIdAndAmt(activityId, receivedAmt);
                }
                DrawCoupon drawCoupon = new DrawCoupon();
                List<String> mobilePhoneList = new ArrayList<>();
                mobilePhoneList.add(payOrder.getCustomerPhone());
                drawCoupon.setCouponIssueIdList(couponIssueIds);
                drawCoupon.setMobilePhoneList(mobilePhoneList);
                drawCoupon.setEnterpriseId(payOrder.getEnterpriseId()); // 添加企业ID
                AjaxResult result = this.sendCoupon(drawCoupon);
            }
        } catch (Exception e) {
            // 处理子方法抛出的异常
            System.out.println("消费后领券发生异常：" + e.getMessage());
        }
    }

    @Override
    public String checkCouponActivity(Integer enterpriseId, PayOrder payOrderInfo, Double amt) {
        BigDecimal receivedAmt = payOrderInfo.getAmt();

//        微信1支付宝2现金3银行卡4电子卡5实体卡6
        String payType = "6";

        Map<String, Object> labelParam = new HashMap<>();
        labelParam.put("mobilePhone", payOrderInfo.getCustomerPhone());
        labelParam.put("enterpriseId", Long.valueOf(enterpriseId));
//        标签
        String labelActivityIds = couponActivityMapper.checkLabelCouponActivity(labelParam);
        List<String> activityIdList = new ArrayList<>();
        Set<String> uniqueActivityIdSet = new HashSet<>();

        if(labelActivityIds!=null &&labelActivityIds!=""){
            String[] uniqueActivityIds = labelActivityIds.split(",");
            for (String activityId : uniqueActivityIds) {
                activityIdList.add(activityId);
                uniqueActivityIdSet.add(activityId);
            }
        }
//        会员级别
        String userMemberLevel = this.getAppUserGrowLevel(payOrderInfo.getCustomerPhone(), Long.valueOf(enterpriseId));
        Map<String, Object> param = new HashMap<>();
        param.put("enterpriseId", enterpriseId);
        param.put("payType", payType);
        param.put("userMemberLevel", userMemberLevel);
        param.put("activityIds", uniqueActivityIdSet);
        List<String> activityIds = new ArrayList<>();
        if (uniqueActivityIdSet.size() != 0) {
            activityIds = couponActivityMapper.checkCouponActivityOnLabel(param);
        }
        if (activityIds.size() == 0) {
            activityIds = couponActivityMapper.checkCouponActivity(param);
        }
        if (activityIds != null && !activityIds.isEmpty()) {
            Map<String, Object> thresholdParam = new HashMap<>();
            thresholdParam.put("receivedAmt", receivedAmt);
            thresholdParam.put("activityIds", activityIds);
            String activityId = couponActivityMapper.checkThresholdCouponActivity(thresholdParam);
            return activityId;
        } else {
            return "0";
        }
    }

    @Override
    public String getAppUserGrowLevel(String mobilePhone, Long enterpriseId) {
        Map<String, Object> param = new HashMap<>();
        param.put("mobilePhone", mobilePhone);
        param.put("enterpriseId", enterpriseId);
        param.put("superName", "年卡");
        String grow = new String();
        String supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "8";
        }
            param.put("superName", "季卡");
             supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "7";
        }
        param.put("superName", "月卡");
        supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "6";
        }
            grow = couponActivityMapper.getGrow(param);
            return grow;
    }

    @Override
    public void insertCouponActivityRelaIssue(Map<String, String> paramMap) {
        couponActivityMapper.insertCouponActivityRelaIssue(paramMap);
    }

    @Override
    public void deleteCouponActivityRelaById(String activityId) {
        couponActivityMapper.deleteCouponActivityRelaById(activityId);
        couponActivityMapper.deleteCouponActivityLadder(activityId);
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    @Override
    public List<String> getIssueIdsByActivityId(String activityId) {
        return couponActivityMapper.getIssueIdsByActivityId(activityId);
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    @Override
    public List<String> getIssueIdsByActivityIdAndAmt(String activityId, BigDecimal receivedAmt) {
        // 获取满足条件的最大 threshold_amt 值
        BigDecimal thresholdAmt = couponActivityMapper.getThresholdAmtByActivityIdAndAmt(activityId, receivedAmt);

        if (thresholdAmt != null) {
            // 根据最大 threshold_amt 值获取对应的 issue_id 列表
            List<String> issueIds = couponActivityMapper.getIssueIdsByThresholdAmt(activityId, thresholdAmt);
            return issueIds;
        } else {
            // 如果 thresholdAmt 为 null，表示没有符合条件的数据
            return new ArrayList<>();
        }
    }
}
